package com.baidu.udpDemo1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Server {
    public static void main(String[] args) throws Exception {
        //1.创建接收消息的人 这个必须指定端口
        DatagramSocket datagramSocket = new DatagramSocket(9999);

        //2.创建一个64k的字节数组用于接收数据 最大64k
        byte[] bytes = new byte[1024 * 64];

        //3.创建数据包 用于接收消息
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

        //4.循环读取发送的消息
        while (true){
            //4.1.接收消息
            datagramSocket.receive(datagramPacket);

            //4.2.确定收到消息的长度
            int length = datagramPacket.getLength();

            //4.3.转成字符串输出
            String msg = new String(bytes, 0, length);
            InetAddress inetAddress = datagramPacket.getAddress();
            String hostAddress = inetAddress.getHostAddress();
            System.out.println("来自" + hostAddress + ",端口为:" + datagramPacket.getPort() + "发送的消息:" + msg);
        }
    }
}
